#include<sys/wait.h>
#include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
//阻塞等待
#if 0
int main()
{
    pid_t id = fork();
    if(id == 0) //child
    {
        int count = 5;
        while(count--)
        {
            printf("I am child....pid:%d ppid:%d\n",getpid(),getppid());
            sleep(1);
        }
        printf("child exit....\n");
        exit(0);
    }
    else if(id < 0)
    {
        perror("fork :");
        exit(1);
    }
    //parent
    //父进程干自己的事情....

    // 使用wait函数：wait(NULL); / wait(&status)  等待任意一个子进程退出
    int status = 0;
    //int ret = waitpid(-1,NULL,0);//阻塞等待任意一个子进程,不关心子进程退出信息
    //int ret = waitpid(-1,&status,0);//阻塞等待任意一个子进程
    int ret = waitpid(id,&status,0);//阻塞等待pid为id的子进程
    if(ret > 0)
    {
        printf("father wait child:pid %d success\n",ret);
        printf("exitCode:%d   exitSignal:%d\n",(status>>8)&0xff,(status&0x7f));
    }
    else
    {
        perror("waitpid:");
        exit(1);
    }
    return 0;
}
#endif

//非阻塞等待->轮询检测
int main()
{
    pid_t id = fork();
    if(id == 0)
    {
        int count = 10;
        while(count--)
        {
            printf("I am child....pid:%d ppid:%d\n",getpid(),getppid());
            sleep(1);
        }
        printf("child exit....\n");
        exit(0);
    }
        else if(id < 0)
    {
        perror("fork :");
        exit(1);
    }
    // 使用wait函数：wait(NULL); / wait(&status)  等待任意一个子进程退出
    int status = 0;
    int ret = 0;
    while((ret = waitpid(id,&status,WNOHANG) )== 0)//非阻塞等待时,无子进程退出返回0
    {
        printf("father running...\n");//子进程没有退出，父进程干自己的事
        sleep(2);
    }
    if(ret > 0)
    {
        printf("father wait child:pid %d success\n",ret);
        printf("exitCode:%d   exitSignal:%d\n",(status>>8)&0xff,(status&0x7f));
    }
    else
    {
        perror("waitpid:");
        exit(1);
    }
    return 0;
}